<?php
namespace app\designer\library\database;

use app\designer\library\Database;

class mysql extends Database{

    public function getTableList()
    {
        return $this->db->query("SELECT TABLE_NAME as `table` ,TABLE_COMMENT as `comment`  FROM information_schema.TABLES WHERE TABLE_SCHEMA = '".$this->getDatabaseName()."'");
    }

    public function getTableInfo(string $table)
    {

        $config = $this->db->getConfig();

        return $this->db->query("DESCRIBE `".$this->getDatabaseName()."`.".$table);
    }

    public function getTableField(string $table)
    {
        $info = $this->getTableInfo($table);
        $re = [];
        if (is_array($info)){
            for ($i=0; $i<count($info); $i++){
                if ($info[$i]['Key']=='PRI'){
                    //放第一个
                    array_unshift($re,$info[$i]['Field']);
                }else{
                    $re[] = $info[$i]['Field'];
                }
            }
        }

        return $re;
    }

    public function getTableComment(string $table){
        //获取表注释
        $sql = "SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '".$this->getDatabaseName()."' AND TABLE_NAME = '".$table."'";
        $data = $this->db->query($sql);
        if (!$data){
            return $data[0]['TABLE_COMMENT'];
        }else{
            return '';
        }
    }

    public function getCreateTableSQL(string $table){
        
        $data = $this->db->query("SHOW CREATE TABLE `".$this->getDatabaseName()."`.".$table);
        
        if (!$data){
            return '';
        }else{

            $sql = $data[0]['Create Table'];

            //去掉AUTO_INCREMENT
            $sql = preg_replace('/AUTO_INCREMENT=\d+/','',$sql);

            return $sql;
        }
        
    }

   
}